package com.设计模式;

public class SingletonDemo
{
    //    一般的写法
    private static SingletonDemo singletonDemo = null;

//    多线程安全写法
//    private static volatile SingletonDemo singletonDemo2;

    //    饿汉式
    public static SingletonDemo getInstance1()
    {
        singletonDemo = new SingletonDemo();
        return singletonDemo;
    }

    //    懒汉式
    public static SingletonDemo getInstance2()
    {
        if (singletonDemo == null)
        {
            singletonDemo = new SingletonDemo();
        }
        return singletonDemo;
    }

    //    多线程的双端检索机制
    public static SingletonDemo getInstance3()
    {
        if (singletonDemo == null)
        {
            synchronized (SingletonDemo.class)
            {
                if (singletonDemo == null)
                {
                    singletonDemo = new SingletonDemo();
                }
            }
        }
        return singletonDemo;
    }

    //    通过静态工厂的方式
    private static class InnerClass
    {
        public static SingletonDemo singletonDemo = new SingletonDemo();
    }

    public static SingletonDemo getInstance4()
    {
        return InnerClass.singletonDemo;
    }
}
